<template>
  <el-dialog
    :title="title"
    :model-value="modelValue"
    @close="closed"
  >
    <el-form :model="addForm">
      <el-form-item label="姓 名" :label-width="formLabelWidth" required>
        <el-input v-model="addForm.username" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="手 机" :label-width="formLabelWidth">
        <el-input v-model="addForm.mobile" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="头 像" :label-width="formLabelWidth">
        <el-upload
          class="avatar-uploader"
          accept=".png,.jpg,.jpeg"
          :action="uploadUrl"
          :headers="uploadHeaders"
          :name="uploadFieldName"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload">
          <img v-if="imageUrl" :src="imageUrl" class="avatar">
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="密 码" :label-width="formLabelWidth" required>
        <el-input v-model="addForm.password" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="确认密码" :label-width="formLabelWidth" required>
        <el-input v-model="addForm.password_confirm" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="分配角色" :label-width="formLabelWidth">
        <el-checkbox-group v-model="addForm.roles">
          <el-checkbox
            v-for="item in allRoleList"
            :label="item.title"
            :key="item.id"
          />
        </el-checkbox-group>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closed">{{ $t('msg.universal.cancel') }}</el-button>
        <el-button type="primary" @click="onConfirm">{{
          $t('msg.universal.confirm')
        }}</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { defineProps, defineEmits, ref, reactive, watch } from 'vue'
import { roleList } from '@/api/role'
import { createUser, userDetail, updateUser } from '@/api/user-manage'
import { watchSwitchLang } from '@/utils/i18n'
import { ElMessage } from 'element-plus'
import { useI18n } from 'vue-i18n'
import { Plus } from '@element-plus/icons-vue'
import store from '@/store'

const title = ref('添加员工')
const imageUrl = ref('')
const formLabelWidth = ref('80px')

const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true
  },
  userId: {
    type: String,
    required: true
  }
})

// 设置上传时携带的 headers
const token = store.getters.token
const uploadHeaders = ref({
  Authorization: `Bearer ${token}`
})
const uploadUrl = ref(process.env.VUE_APP_BASE_API + '/user-manage/upload')
const uploadFieldName = ref('avatar') // 设置上传字段名

const handleAvatarSuccess = (res, uploadFile) => {
  if (res && res.success) {
    imageUrl.value = res.data.avatar
    addForm.avatar = res.data.avatar
    ElMessage.success('图片上传成功！')
  } else {
    if (res && res.msg) {
      ElMessage.error(res.msg)
    } else {
      ElMessage.error('图片上传失败！')
    }
  }
}

// 上传文件前检验
const beforeAvatarUpload = (rawFile) => {
  // console.log(rawFile)
  const type = ['image/jpeg', 'image/jpg', 'image/png']
  if (type.indexOf(rawFile.type) === -1) {
    ElMessage.error('上传的文件支持JPG、JPEG、PNG')
    return false
  } else if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error('图片大小不能超过10MB!')
    return false
  }
  return true
}

// 表单属性
const initFormAttr = {
  username: '',
  mobile: '',
  avatar: '',
  password: '',
  password_confirm: '',
  roles: []
}
const addForm = reactive({ ...initFormAttr })

const emits = defineEmits(['update:modelValue', 'reflushRole'])

const closed = () => {
  emits('update:modelValue', false)
  resetForm()
}

// 重置表单数据
const resetForm = () => {
  Object.assign(addForm, initFormAttr)
  imageUrl.value = ''
}

// 获取所有角色
const allRoleList = ref([])
const getRoleListData = async () => {
  allRoleList.value = await roleList()
}
getRoleListData()
watchSwitchLang(getRoleListData)

// 获取当前用户
const getUserDetail = async () => {
  const res = await userDetail(props.userId)
  addForm.roles = res.roles.map(role => role.title)
  addForm.username = res.username
  addForm.mobile = res.mobile
  addForm.avatar = res.avatar
  imageUrl.value = res.avatar
  title.value = '编辑员工'
}

watch(
  () => props.userId,
  (val) => {
    if (val) getUserDetail()
  }
)

const i18n = useI18n()
const onConfirm = async () => {
  const roles = addForm.roles.map((title) => {
    return allRoleList.value.find((role) => role.title === title)
  })

  if (props.userId) {
    await updateUser(props.userId, addForm, roles)
    ElMessage.success(i18n.t('msg.form.editSuccess'))
  } else {
    await createUser(addForm, roles)
    ElMessage.success(i18n.t('msg.from.createSuccess'))
  }

  emits('reflushRole')
  closed()
}
</script>
<style scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 60px;
    height: 60px;
    line-height: 60px;
    text-align: center;
  }
  .avatar {
    width: 60px;
    height: 60px;
    display: block;
  }
</style>